<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'library/google/Google_Client.php';
require_once 'library/google/contrib/Google_AnalyticsService.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");

// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('1033467813708.apps.googleusercontent.com');
$client->setClientSecret('LqiZkAs1e6lFj7CaCxE5xnE3');
$client->setRedirectUri('http://beforever.info/assets/api/google_analytics.php');
$client->setDeveloperKey('AIzaSyDSIpLBRHFiu6LdX7vQgyM_mg6n5Rxjg9U');
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  //$props = $service->management_webproperties->listManagementWebproperties("~all");
  //print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";

  //$accounts = $service->management_accounts->listManagementAccounts();
  //print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";

  //$segments = $service->management_segments->listManagementSegments();
  //print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";

  //$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
  //print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";
	
  $_SESSION['token'] = $client->getAccessToken();

	$projectId = '65518026';

	// metrics
	$_params[] = 'date';
	$_params[] = 'date_year';
	$_params[] = 'date_month';
	$_params[] = 'date_day';
	// dimensions
	$_params[] = 'visits';
	$_params[] = 'newVisits';
	$_params[] = 'pageviews';
	$_params[] = 'bounces';
	$_params[] = 'entrance_bounce_rate';
	$_params[] = 'visit_bounce_rate';
	$_params[] = 'avg_time_on_site';
	
	$from = date('Y-m-d', strtotime('-1 month')); // 1 month
	$to = date('Y-m-d'); // today
	
	$metrics = 'ga:visits,ga:newVisits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
	$dimensions = 'ga:date,ga:year,ga:month,ga:day';
	$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

	$content = 'date'.chr(9).'year'.chr(9).'month'.chr(9).'day'.chr(9).'visits'.chr(9).'newVisits'.chr(9).'pageviews'.chr(9).'bounces'.chr(9).'entranceBounceRate'.chr(9).'visitBounceRate'.chr(9).'avgTimeOnSite'."\n";
	$fp = fopen("data/dataAnalytics.txt","w");
	fwrite($fp,$content);
	fclose($fp);
	$content = "";
	foreach($data['rows'] as $item){
		$count = count($item);
		foreach($item as $key => $value){
			if($key == ($count-1)){
				$content .= $value."\n";
			}else{
				$content .= $value.chr(9);
			}
			
		}
	}
	$fp = fopen("data/dataAnalytics.txt","a");
	fwrite($fp,$content);
	fclose($fp);
	
	unset($_params);
	// metrics
	$_params[] = 'date_year';
	$_params[] = 'date_month';
	$_params[] = 'date_day';
	// dimensions
	$_params[] = 'visitors';
	$_params[] = 'newVisits';

	$from = date('Y-m-d', strtotime("-1 month", time()));
	$form_header = date("F j, Y",strtotime($from));
	$to = date('Y-m-d'); // today
	$to_header = date("F j, Y",strtotime($to));

	$metrics = 'ga:visitors,ga:newVisits';
	$dimensions = 'ga:year,ga:month,ga:day';
	$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

	$data_final = array();
	foreach($data['rows'] as $row) {
	   	$dataRow = array();
		$data_final1 = array();
	   	foreach($_params as $colNr => $column){
			$data_final1[$column] = $row[$colNr];	
		}
		$data_final[] = $data_final1;
	}
	foreach($data_final as $item){
		$date = $item['date_year']."-".$item['date_month']."-".$item['date_day'];
		unset($item['date_day'],$item['date_month'],$item['date_year']);
		$date_final['date'] = date("l, F j, Y",strtotime($date));
		array_unshift($item,$date_final['date']);
		$result = implode("\t",$item);
		$result_final[] = $result;
	}
	$content = "# ----------------------------------------
www.beforever.info
Daily visits
".$form_header."	".$to_header."
# ----------------------------------------

# ----------------------------------------
# Graph
# ----------------------------------------"."\n";
$content .= "Day"."\t"."All Visits (Segment)"."\t"."New Visitors (Segment)"."\n";
$sub_content = implode("\n",$result_final);
$content .= $sub_content."\n";
$content .= "\n";
$content .= "# ----------------------------------------
# Table
# ----------------------------------------"."\n";
	$fp = fopen('data/analytics.tsv', "w"); 
	fwrite($fp, $content); 
	fclose($fp);
	
} else {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";
}